package com.study.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.study.model.mdao.TousuDAO;
import com.study.services.DeptService;
import com.study.services.TousuService;
import com.study.services.WeixiuService;
import com.study.services.WeixiuTableService;

@Controller
public class WeixiuController {
	@Autowired
	WeixiuService service;
	@Autowired
	DeptService deptService;
	@Autowired
	WeixiuTableService weixiuTableService;

	@GetMapping("/weixiutys")
	public ModelAndView getForm5() {
		ModelAndView mv = new ModelAndView("afterSale/kehuweixiu");
		mv.addObject("weixiuresult", service.selectByResult());
		return mv;
	}

	/**
	 * 查看维修（第一次进入）
	 */
	@RequestMapping("/weixiuty")
	@ResponseBody
	public String service1(HttpSession session) {
		Integer cusid = (Integer) session.getAttribute("cusview");
		List<JSONObject> list = service.selectBySel(1, 6, "", "", cusid);
		// pagerhelper自定的PageInfo类.会把ArrayList的信息，整合到PageInfo对象中的list属性中。JSON亦然
		PageInfo<JSONObject> pager = new PageInfo<JSONObject>(list);
		String json = JSONObject.toJSONString(pager);
		// System.out.println(json);
		session.removeAttribute("cusview");
		return json;
	}

	/**
	 * 进入新建维修
	 * 
	 * @return
	 */
	@GetMapping("/weixiu2")
	public ModelAndView getForm2() {
		ModelAndView mv = new ModelAndView("/afterSale/addweixiu");
		mv.addObject("weixiu", new JSONObject());
		mv.addObject("dept", deptService.findDeptByPar(3));
		mv.addObject("weixiuLess", new JSONObject());
		return mv;
	}

	/**
	 * 分页+全部+带条件查询 ty
	 * 
	 * @return
	 */
	@PostMapping("/afterSale/kehuweixiu")
	@ResponseBody
	public String getForm3(String input, String selects, int currentPage, int pagesize) {
		System.out.println(currentPage + "currentPage");
		System.out.println(pagesize + "pagesize");
		System.out.println(input);
		System.out.println(selects);

		List<JSONObject> list = service.selectBySel(currentPage, pagesize, input.trim(), selects.trim(), 0);

		PageInfo<JSONObject> pager = new PageInfo<JSONObject>(list);
		String json = JSONObject.toJSONString(pager);

		System.out.println("我是投诉里面的带条件查询");
		for (JSONObject jsonObject : list) {
			System.out.println(jsonObject);
		}
		return json;
	}

	/**
	 * 添加维修
	 * 
	 * @param name
	 * @param type
	 * @param dept
	 * @param custid
	 * @param date1
	 * @param user
	 * @param linId
	 * @param phone
	 * @param money
	 * @param cat
	 * @param repair
	 * @param address
	 * @param state
	 * @param desc
	 * @return
	 */
	@PostMapping("weixiuform")
	@ResponseBody
	public boolean addForm(String theme, String custid, String goodid, String order, Date date1, String dept,
			String user, String linId, String phone, String money, String cat, String address, String desc,
			String isTimeout, String custname, HttpSession session) {

		Integer useid = (Integer) session.getAttribute("useid");
		boolean result = service.addWeixiu(theme, custid, goodid, order, date1, dept, user, linId, phone, money, cat,
				address, desc, useid + "", isTimeout, custname);

		System.out.println(result + "我是维修工单的结果");
		return result;
	}

	/**
	 * 删除投诉
	 * 
	 * @param goo_id
	 * @return
	 */
	@PostMapping("/delWeixiu")
	@ResponseBody
	public String delete(Integer c_id) {
		System.out.println(c_id);
		service.delete(c_id);
		return "ok";
	}

	/**
	 * 编辑服务
	 * 
	 * @param theme
	 * @param user
	 * @param type
	 * @param dates
	 * @param times
	 * @param custname
	 * @param degree
	 * @param progress
	 * @param aresult
	 * @param spendtime
	 * @param feedback
	 * @param linkman
	 * @param more
	 * @return
	 */
	@PostMapping("/editerweixiuform")
	@ResponseBody
	public boolean editorForm(String id, String phone, String cat, String state, String desc, String more,
			Date comdate) {
		System.out.println(id + "编辑维修");
		boolean result = service.editorService(id, phone, cat, state, desc, more, comdate);
		System.out.println(result + "我是售后维修的结果");
		return result;
	}

	/**
	 * 编辑
	 */
	@GetMapping("weixiuEditor")
	public ModelAndView addCustomerByColle(HttpServletRequest request, HttpSession session) {
		String parameter = request.getParameter("id");
		JSONObject weixiu = service.selectBycid(parameter);
		JSONObject object = weixiuTableService.queryById(parameter);
		ModelAndView mv = new ModelAndView("/afterSale/addcontract");
		mv.addObject("weixiu", weixiu);
		mv.addObject("weixiuTabledetail", object);
		JSONArray array = weixiuTableService.getPeiJianCart(parameter);
		session.setAttribute("PeiJianCart1", array);
		return mv;
	}

	/**
	 * 根据custid查询对应的可维修的订单
	 */
	@RequestMapping("/afterSale/queryOrder")
	@ResponseBody
	public List<JSONObject> findOrderAndGoods(String custid) {
		List<JSONObject> orders = service.findOrderAndGoods(custid);
		return orders;
	}

	/**
	 * 根据oid查询对应的订单详情（产品）
	 */
	@RequestMapping("/afterSale/queryGoods")
	@ResponseBody
	public List<JSONObject> findGoods(Integer oid) {
		List<JSONObject> goods = service.findGoods(oid);
		System.out.println(oid + "我是订单id");
		// System.out.println(goods);
		return goods;
	}

	/**
	 * 查询商品是否在保质期内 true在保质期内 false不在保质期内
	 */
	@RequestMapping("/afterSale/isTimeout")
	@ResponseBody
	public boolean isTimeout(Integer oid, Integer gid) {
		System.out.println(oid + "我是订单id+gid" + gid);
		boolean result = service.isTimeout(oid, gid);

		return result;
	}

	/**
	 * 保存一部分维修工单的信息
	 */
	@RequestMapping("/afterSale/setsession")
	@ResponseBody
	public String saveLess(String theme, String custname, String custid, Date date1, String linName, String linId,
			String phone, Integer cat, String goodname, String goodid, String order, String orderName, String isTimeout,
			String desc, HttpServletRequest request) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		JSONObject obj = new JSONObject();
		if (date1 != null) {
			String format2 = format.format(date1);
			obj.put("date1", format2);
		}
		obj.put("custname", custname);
		obj.put("custid", custid);
		obj.put("phone", phone);
		obj.put("cat", cat);
		obj.put("desc", desc);
		obj.put("isTimeout", isTimeout);
		obj.put("theme", theme);

		// 封装订单
		List<JSONObject> list = new ArrayList<>();
		JSONObject orders = new JSONObject();
		orders.put("o_id", order);
		orders.put("otitle", orderName);
		list.add(orders);

		// 封装商品
		JSONObject goods = new JSONObject();
		orders.put("goodid", goodid);
		orders.put("goodname", goodname);
		list.add(goods);

		// 封装联系人
		JSONObject linkman = new JSONObject();
		orders.put("linId", linId);
		orders.put("linName", linName);
		list.add(linkman);

		obj.put("order", list);

		System.out.println("我进来啦" + obj);
		HttpSession session = request.getSession();
		session.setAttribute("weixiuLess", obj);
		return "ss";
	}

	@GetMapping("/weixiu3")
	public ModelAndView is(HttpSession session, HttpServletRequest request) {
		System.out.println("我进来了");
		JSONObject object1 = (JSONObject) session.getAttribute("weixiuLess");
		ModelAndView mv = new ModelAndView("/afterSale/serviceTableToWeixiu");
		mv.addObject("weixiu", new JSONObject());
		mv.addObject("dept", deptService.findDeptByPar(3));
		mv.addObject("weixiuLess", object1);
		mv.addObject("service", new JSONObject());
		mv.addObject("order", new JSONObject());
		mv.addObject("good", new JSONObject());
		return mv;
	}

	/**
	 * ty 维修总控台
	 */
	@GetMapping("/getWeixiuTablety2")
	public ModelAndView getForm31(HttpSession session) {
		ModelAndView mv = new ModelAndView("/afterSale/weixiuTable2");

		return mv;
	}

	/**
	 * 修改维修状态为已完成
	 */
	@PostMapping("/changeStateByFinish1")
	@ResponseBody
	public boolean changeStateByFinish(String id, String rate, String remark, Integer cusid, HttpSession session) {
		Integer useid = (Integer) session.getAttribute("useid");
		// 修改执行状态
		boolean result1 = weixiuTableService.changeState(id, 462, null, null, useid, cusid);

		// 添加评价
		boolean result2 = weixiuTableService.changeRate(id, rate, remark);
		System.out.println(id);
		if (result1 && result2) {
			System.out.println("修改成功");
			return true;
		} else {
			System.out.println("修改失败");
			return false;
		}
	}

	@PostMapping("/uploadWeixiu")
	@ResponseBody
	public String upload(MultipartFile file, Integer repId, HttpServletRequest request) {
		System.out.println("======维修:" + repId);
		try {
			ServletContext context = request.getServletContext();
			String newname = UUID.randomUUID().toString().toUpperCase();
			String suffix = "." + FilenameUtils.getExtension(file.getOriginalFilename());

			// File new_file=new
			// File("D:\\Users\\Administrator\\git\\CRM1\\src\\main\\resources\\static\\repImg"+"/"+newname+suffix);
			File new_file = new File("D:\\Users\\Administrator\\git\\CRM\\src\\main\\resources\\static\\repImg" + "/"
					+ newname + suffix);
			String rep_img = "/repImg/" + newname + suffix;
			file.transferTo(new_file);

			if (repId != null) {
				boolean result = service.addImg(repId, rep_img);
				System.out.println("我是添加图片" + result);
			}
			return newname;

		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
